﻿using EnvDTE;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace Axiom.CodeManifold
{
	public class ServiceManager
	{
		private ServiceDefinition _interface;
		private string _namespace;
		private string _aggregate;

		public ServiceManager(CodeInterface @interface)
		{
			_namespace = @interface.Namespace.Name;
			Service = GetInterface(@interface);
		}

		public ServiceDefinition Service
		{
			get { return _interface; }
			set { _interface = value; }
		}

		/// <summary>
		/// Convert CodeInterface to presentable form
		/// </summary>
		/// <param name="interface"></param>
		/// <returns></returns>
		private ServiceDefinition GetInterface(CodeInterface @interface)
		{
			_interface = new ServiceDefinition()
			{
				Name = @interface.Name,	
			};

			List<MethodDefinition> methods = new List<MethodDefinition>();
			foreach (CodeElement member in @interface.Members)
			{
				if (member.Kind != vsCMElement.vsCMElementFunction)
				{
					continue;
				}
				var method = GetMethod(member as CodeFunction);
				methods.Add(method);
			}

			methods.Sort((a, b) => { return a.Name.CompareTo(b.Name); });
			_interface.Methods = new List<MethodDefinition>(methods);
			return _interface;
		}

		/// <summary>
		/// Convert CodeFunction to presentable form
		/// </summary>
		/// <param name="function"></param>
		/// <returns></returns>
		private MethodDefinition GetMethod(CodeFunction function)
		{
			MethodDefinition method = new MethodDefinition();

			method.Name = function.Name;
			method.Namespace = _namespace;
			method.Aggregate = _interface.Aggregate;
			method.ReturnType = function.Type.GetTypeAsString();
			method.Comment = function.Comment;
			method.DocComment = function.DocComment;
			foreach (CodeParameter parameter in function.Parameters)
			{
				var parametername = parameter.Name;
				var parametertype = parameter.Type.GetTypeAsString();				
				method.Parameters.Add(new Parameter() { Name = parametername, Type = parametertype });
			}

			method.Store();
			return method;
		}
	}
}
